package cn.cloud.all.security.crypto.password;

import cn.cloud.all.security.crypto.codec.Hex;
import cn.cloud.all.security.crypto.codec.Utf8;
import cn.cloud.all.security.crypto.keygen.BytesKeyGenerator;
import cn.cloud.all.security.crypto.keygen.KeyGenerators;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import static cn.cloud.all.security.crypto.EncodingUtils.concatenate;
import static cn.cloud.all.security.crypto.EncodingUtils.subArray;

public class Pbkdf2PasswordEncoder implements PasswordEncoder {

    private static final int DEFAULT_HASH_WIDTH = 256;
    private static final int DEFAULT_ITERATIONS = 185000;

    private final BytesKeyGenerator saltGenerator = KeyGenerators.secureRandom();

    private final byte[] secret;
    private final int hashWidth;
    private final int iterations;
    private String algorithm = SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1.name();
    private boolean encodeHashAsBase64;

    public Pbkdf2PasswordEncoder() {
        this("");
    }

    public Pbkdf2PasswordEncoder(CharSequence secret) {
        this(secret, DEFAULT_ITERATIONS, DEFAULT_HASH_WIDTH);
    }

    public Pbkdf2PasswordEncoder(CharSequence secret, int iterations, int hashWidth) {
        this.secret = Utf8.encode(secret);
        this.iterations = iterations;
        this.hashWidth = hashWidth;
    }

    /**
     * Sets the algorithm to use. See
     * <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SecretKeyFactory">SecretKeyFactory Algorithms</a>
     *
     * @param secretKeyFactoryAlgorithm the algorithm to use (i.e.
     *                                  {@code SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1},
     *                                  {@code SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256},
     *                                  {@code SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512})
     * @since 5.0
     */
    public void setAlgorithm(SecretKeyFactoryAlgorithm secretKeyFactoryAlgorithm) {
        if (secretKeyFactoryAlgorithm == null) {
            throw new IllegalArgumentException("secretKeyFactoryAlgorithm cannot be null");
        }
        String algorithmName = secretKeyFactoryAlgorithm.name();
        try {
            SecretKeyFactory.getInstance(algorithmName);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Invalid algorithm '" + algorithmName + "'.", e);
        }
        this.algorithm = algorithmName;
    }

    public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
        this.encodeHashAsBase64 = encodeHashAsBase64;
    }

    @Override
    public String encode(CharSequence rawPassword) {
        byte[] salt = this.saltGenerator.generateKey();
        byte[] encoded = encode(rawPassword, salt);
        return encode(encoded);
    }

    private String encode(byte[] bytes) {
        if (this.encodeHashAsBase64) {
            return Base64.getEncoder().encodeToString(bytes);
        }
        return String.valueOf(Hex.encode(bytes));
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        byte[] digested = decode(encodedPassword);
        byte[] salt = subArray(digested, 0, this.saltGenerator.getKeyLength());
        return MessageDigest.isEqual(digested, encode(rawPassword, salt));
    }

    private byte[] decode(String encodedBytes) {
        if (this.encodeHashAsBase64) {
            return Base64.getDecoder().decode(encodedBytes);
        }
        return Hex.decode(encodedBytes);
    }

    private byte[] encode(CharSequence rawPassword, byte[] salt) {
        try {
            PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), concatenate(salt, this.secret), this.iterations, this.hashWidth);
            SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm);
            return concatenate(salt, skf.generateSecret(spec).getEncoded());
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("Could not create hash", e);
        }
    }

    public enum SecretKeyFactoryAlgorithm {
        PBKDF2WithHmacSHA1,
        PBKDF2WithHmacSHA256,
        PBKDF2WithHmacSHA512
    }
}
